package com.warrantyhotel.android.ui.map;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.warrantyhotel.android.R;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.ui.NearbyStoresDetail;
import com.warrantyhotel.android.util.OnRedirectToListStores;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.android.util.imLoader1.ImageLoaderNew1;
import com.warrantyhotel.android.util.imLoader2.Utils;

public class PlaceOverlay extends ItemizedOverlay<MyOverlayItem> {

	private static final int KOEFF = 10;
	private ArrayList<MyOverlayItem> myOverlaysAll = new ArrayList<MyOverlayItem>();
	private ArrayList<MyOverlayItem> myOverlays = new ArrayList<MyOverlayItem>();
	private MapView mapView;
	private OnRedirectToListStores onRedirectToListStores;
	private ImageLoaderNew1 im;
	private LayoutInflater mInflater;

	public PlaceOverlay(Drawable defaultMarker, MapView mapView, OnRedirectToListStores onRedirectToListStores) {
		// super(boundCenterBottom(defaultMarker));
		super(defaultMarker);
		this.mapView = mapView;
		this.onRedirectToListStores = onRedirectToListStores;
		im = new ImageLoaderNew1(mapView.getContext());
		mInflater = (LayoutInflater) mapView.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		populate();
	}

	public void addOverlay(MyOverlayItem overlay) {
		myOverlaysAll.add(overlay);
		myOverlays.add(overlay);
	}

	public void doPopulate() {
		populate();
		setLastFocusedIndex(-1);
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		if (!shadow)
			super.draw(canvas, mapView, shadow);
	}

	@Override
	protected MyOverlayItem createItem(final int i) {
		int count = myOverlays.get(i).getList().size();
		final Bitmap pinBg = BitmapFactory.decodeResource(mapView.getContext().getResources(), R.drawable.map_marker_logo);
		try {
			if (count == 0) {
				String url = myOverlays.get(i).getThumbnail();
				im.displayImage(url, (Activity) mapView.getContext(), new ImageLoaderNew1.OnFetchCompleteListener1() {
					@Override
					public void onFetchComplete1(Bitmap result) {
						if (result != null) {

							Bitmap bitmapWithReflection = Bitmap.createBitmap(pinBg.getWidth(), pinBg.getHeight(), Config.ARGB_8888);
							Canvas canvas = new Canvas(bitmapWithReflection);

							Paint paint = new Paint();
							paint.setAntiAlias(true);
							int h, w;
							h = result.getHeight();
							w = result.getWidth();
							int res = (h > w) ? w : h;
							result = Utils.getRoundedCornerImage(Bitmap.createBitmap(result, 0, 0, res, res));

							canvas.drawBitmap(pinBg, 0f, 0f, paint);

							DisplayMetrics metrics = new DisplayMetrics();
							((Activity) mapView.getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
							switch (metrics.densityDpi) {
							case DisplayMetrics.DENSITY_LOW:
								result = Bitmap.createScaledBitmap(result, bitmapWithReflection.getWidth() - 10, bitmapWithReflection.getWidth() - 10, true);
								canvas.drawBitmap(result, 5f, 4f, paint);
								break;
							case DisplayMetrics.DENSITY_MEDIUM:
								result = Bitmap.createScaledBitmap(result, bitmapWithReflection.getWidth() - 14, bitmapWithReflection.getWidth() - 14, true);
								canvas.drawBitmap(result, 7f, 6f, paint);
								break;
							case DisplayMetrics.DENSITY_HIGH:
								result = Bitmap.createScaledBitmap(result, bitmapWithReflection.getWidth() - 20, bitmapWithReflection.getWidth() - 20, true);
								canvas.drawBitmap(result, 10f, 8f, paint);
								break;
							}

							Drawable b = new BitmapDrawable(bitmapWithReflection);
							b.setBounds(0 - b.getIntrinsicWidth(), 0 - b.getIntrinsicHeight(), 0, 0);
							MyOverlayItem item = myOverlays.get(i);

							pinBg.recycle();
							result.recycle();

							item.setMarker(b);
							mapView.invalidate();
						}
					}
				});
			} else {

				float coefficient = 1;
				int h = pinBg.getWidth();
				DisplayMetrics metrics = new DisplayMetrics();
				((Activity) mapView.getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);

				switch (metrics.densityDpi) {
				case DisplayMetrics.DENSITY_MEDIUM:
					coefficient = 1;
					break;
				case DisplayMetrics.DENSITY_HIGH:
					coefficient = 2;
					break;
				}

				String countValue = String.valueOf(myOverlays.get(i).getList().size() + 1);
				Bitmap bm = Bitmap.createBitmap(h, h, Config.ARGB_8888);
				View view = mInflater.inflate(R.layout.pin_map, null);
				Canvas canvas = new Canvas(bm);
				view.layout(0, 0, h, h);
				view.draw(canvas);

				// Paint paint = new Paint();
				TextPaint textPaint = new TextPaint();
				textPaint.setTextSize(coefficient * 20f);
				textPaint.setAntiAlias(true);

				textPaint.setTypeface(Typeface.DEFAULT_BOLD);
				float len = textPaint.measureText(countValue);
				textPaint.setColor(mapView.getResources().getColor(R.color.blue_text));
				textPaint.setStyle(Paint.Style.FILL);
				canvas.drawText(countValue, h / 2 - len / 2, h / 2 + (coefficient * 7), textPaint);

				Drawable b = new BitmapDrawable(bm);
				b.setBounds(0 - b.getIntrinsicWidth() / 2, 0 - b.getIntrinsicHeight(), b.getIntrinsicWidth() / 2, 0);

				MyOverlayItem item = myOverlays.get(i);
				item.setMarker(b);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return myOverlays.get(i);
	}

	@Override
	public int size() {
		return myOverlays.size();
	}

	private boolean isImposition(MyOverlayItem item1, MyOverlayItem item2) {
		int latspan = mapView.getLatitudeSpan();
		int delta = latspan / KOEFF;
		double dx = item1.getPoint().getLatitudeE6() - item2.getPoint().getLatitudeE6();
		double dy = item1.getPoint().getLongitudeE6() - item2.getPoint().getLongitudeE6();
		double dist = Math.sqrt(dx * dx + dy * dy);
		if (dist < delta) {
			return true;
		} else {
			return false;
		}
	}

	public void clear() {
		myOverlaysAll.clear();
		myOverlays.clear();
	}

	public void calculateItems() {
		myOverlaysClear();
		boolean isImposition;
		for (MyOverlayItem itemFromAll : myOverlaysAll) {
			isImposition = false;
			for (MyOverlayItem item : myOverlays) {
				if (itemFromAll == item) {
					isImposition = true;
					break;
				}
				if (isImposition(itemFromAll, item)) {
					item.addList(itemFromAll);
					isImposition = true;
					break;
				}
			}
			if (!isImposition) {
				myOverlays.add(itemFromAll);
			}
		}
		doPopulate();
	}

	private void myOverlaysClear() {
		for (MyOverlayItem item : myOverlaysAll) {
			item.getList().clear();
		}
		myOverlays.clear();
	}

	@Override
	protected boolean onTap(int index) {
		if (myOverlays.get(index).getList().size() == 0) {
			String id = myOverlays.get(index).getRetailStoreID();
			String banner = myOverlays.get(index).getBanner();
			GeoPoint point = myOverlays.get(index).getPoint();
			boolean isPOI = myOverlays.get(index).isPOI();

			if (id != null) {
				if (!isPOI) {
					mapView.getController().animateTo(point);
					final Intent intent = new Intent(mapView.getContext(), NearbyStoresDetail.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra(Keys._retailStoreId, id);
					intent.putExtra(Keys.banner, banner);
					mapView.getContext().startActivity(intent);
				} else {
					ToastUtil.showText(mapView.getContext(), myOverlays.get(index).getName() + "\n" + mapView.getContext().getString(R.string.poi));
				}

			}
		} else {
			if (mapView.getZoomLevel() >= 16 /* mapView.getMaxZoomLevel() */) {
				onRedirectToListStores.redirectToList();
			} else {
				mapView.getController().setZoom(mapView.getZoomLevel() + 2);
				mapView.getController().animateTo(myOverlays.get(index).getPoint());
			}
		}

		// Toast.makeText(mapView.getContext(), myOverlays.get(index).getName(),
		// Toast.LENGTH_SHORT).show();
		return true;
	}

}
